package com.hua.Service;
import org.json.JSONObject;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

import com.hua.Dao.SqlService;
import com.hua.Model.UserInfo;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.omg.PortableServer.ID_ASSIGNMENT_POLICY_ID;

import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class funtion {
	// 封装快速方法
	private static int count;
	private static int user_id;
	static HashMap<String, Object> hashMap = new HashMap<>(); // 存放id，name，price
	static Scanner scanner = new Scanner(System.in);

	// 封装一个输入ID，Name，Price函数。值会添加到哈希表，便于后期调用。
	public void input_info(String judege) {
		// 创建一个HashMap对象
		hashMap.clear();
		System.out.println(judege + "\n请设置你的账户ID：");
		int user_id = scanner.nextInt();
		System.out.println("请设置你的昵称：");
		String user_name = scanner.next();
		System.out.println("请设置你的密码：");
		String user_pwd = scanner.next();
		// 使用put方法存储内容
		hashMap.put("id", user_id);
		hashMap.put("name", user_name);
		hashMap.put("pwd", user_pwd);
	}
	
	//封装浏览器打开链接
	public void OpenUrl(String url) {
		try {
            Desktop desktop = Desktop.getDesktop();
            URI uri = new URI(url);
            desktop.browse(uri);
        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        }
	}

	// 后缀判断
	public static boolean isValidFileExtension(String filePath, List<String> validExtensions) {
		File file = new File(filePath);
		String fileName = file.getName();
		int lastIndexOfDot = fileName.lastIndexOf('.');
		if (lastIndexOfDot == -1) {
			return false;
		}
		// 转换小写
		String fileExtension = fileName.substring(lastIndexOfDot + 1).toLowerCase();
		return validExtensions.contains(fileExtension);
	}

	// 判断是否是用户
	public Boolean is_account(String phone) {
		SqlService sqlService = new SqlService();
		try {
			if (sqlService.is_account(phone) == false) {
				// 不存在用户
				return false;
			} else {
				return true;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 默认是
		return true;
	}

	// 查询存储容量
	public int query_storage(int id) {
		SqlService sqlService = new SqlService();
		int Storage = 0;
		try {
			Storage = sqlService.GetStorage(id);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return Storage;
	}

	// 封装一个判断，判断返回的count是否存在，即是否运行成功，影响了行
	public void judge_count(int count, String change) {
		if (count > 0) {
			System.out.println("数据" + change + "成功\n");
		} else {
			System.out.println("数据" + change + "失败\n");
		}
	}

	// 基础字符串检验函数
	public static boolean check_str(String input, String type) {
		if (input == null || input.length() == 0) {
			// 传入为空
			return false;
		} else {
			if (type.equals("含特殊")) {
				// 定义一个正则表达式，用于匹配特殊字符
				String regex = "[!@#$%^&*()，,]";
				// 使用正则表达式的matches方法判断输入字符串是否为特殊字符
				return input.matches(regex);
			} else if (type.equals("全数字")) {
				for (int i = 0; i < input.length(); i++) {
					if (!Character.isDigit(input.charAt(i))) {
						return false;
					}
				}
				return true;
			} else if (type.equals("全字母")) {
				for (int i = 0; i < input.length(); i++) {
					char c = input.charAt(i);
					if (!Character.isLetter(c)) {
						return false;
					}
				}
				return true;
			} else if (type.equals("含中文")) {
				for (char c : input.toCharArray()) {
					if (Character.UnicodeScript.of(c) == Character.UnicodeScript.HAN) {
						System.out.println("含有中文");
						return true;
					}
				}
				return false;
			} else if (type.equals("账户")) {
				for (char c : input.toCharArray()) {
					if (!Character.isLetterOrDigit(c) && c != '@' && c != '.') {
						System.out.println("账户检测异常");
						funtion.wanr_tips("账户设置", "账户只能为手机号码或邮箱");
						return false;
					}
				}
				return true;
			} else if (type.equals("网址")) {
				String regex = "^(http|https|ftp)://[^\\s/$.?#].[^\\s]*$";
				Pattern pattern = Pattern.compile(regex);
				Matcher matcher = pattern.matcher(input);
				return matcher.matches();
			}
		}
		return false;
	}

	// SHA256加密
	public String encryptSHA256(String input) {
		try {
			MessageDigest digest = MessageDigest.getInstance("SHA-256");
			byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8));
			StringBuilder hexString = new StringBuilder();
			for (byte b : hash) {
				String hex = Integer.toHexString(0xff & b);
				if (hex.length() == 1) {
					hexString.append('0');
				}
				hexString.append(hex);
			}
			return hexString.toString();
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("无法找到SHA-256算法", e);
		}
	}

	// 弹窗提示层
	public static void tips(String title, String content) {
		JFrame frame = new JFrame("弹窗提示");
		JOptionPane.showMessageDialog(frame, content, title, JOptionPane.INFORMATION_MESSAGE);
	}

	// 弹窗警告提示层
	public static void wanr_tips(String title, String content) {
		JFrame frame = new JFrame("弹窗提示");
		JOptionPane.showMessageDialog(frame, content, title, JOptionPane.WARNING_MESSAGE);
	}

	// 弹窗错误提示层
	public static void faild_tips(String title, String content) {
		JOptionPane.showMessageDialog(null, content, title, JOptionPane.ERROR_MESSAGE);
	}

	// 弹窗警告提示层
	public static int areYouOk_tips(String title, String content) {
		int n = JOptionPane.showConfirmDialog(null, content, title, JOptionPane.YES_NO_CANCEL_OPTION);
		return n;
	}

	// 弹窗输入提示层
	public static String input(String title, String content) {
		String name = JOptionPane.showInputDialog(null, content, title, JOptionPane.PLAIN_MESSAGE);
		return name;
	}

	// 使用POST请求Python Flask服务地址，实现相关Api操作
	// 文件夹构建
	public String build_floder(String account, String password) {
		String url = "http://10.157.0.7:6767/bulid"; // 请求URL
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost build = new HttpPost(url);
		MultipartEntityBuilder builder = MultipartEntityBuilder.create();

		builder.addTextBody("account", account, ContentType.TEXT_PLAIN);
		builder.addTextBody("password", password, ContentType.TEXT_PLAIN);

		HttpEntity multipart = builder.build();
		build.setEntity(multipart);

		CloseableHttpResponse response = null;
		String responseContent = null;
		try {
			response = httpClient.execute(build);
			HttpEntity responseEntity = response.getEntity();
			responseContent = EntityUtils.toString(responseEntity);
			// System.out.println("POST Response is: " + responseContent);
		} catch (IOException e) {
			e.printStackTrace();
			return "失败";
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
					return "失败";
				}
			}
		}
		return responseContent;
	}

	// 删除文件
	public String delete_file(String account, String password, String filePath,String filesID) {
		String url = "http://10.157.0.7:6767/manage/delete"; // 请求URL
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost build = new HttpPost(url);
		MultipartEntityBuilder builder = MultipartEntityBuilder.create();

		builder.addTextBody("account", account, ContentType.TEXT_PLAIN);
		builder.addTextBody("password", password, ContentType.TEXT_PLAIN);
		builder.addTextBody("filesID", filesID, ContentType.TEXT_PLAIN);
		builder.addTextBody("file_path", URLEncoder.encode(filePath), ContentType.TEXT_PLAIN);
		System.out.println(filePath);
		HttpEntity multipart = builder.build();
		build.setEntity(multipart);

		CloseableHttpResponse response = null;
		String responseContent = null;
		try {
			response = httpClient.execute(build);
			HttpEntity responseEntity = response.getEntity();
			responseContent = EntityUtils.toString(responseEntity);
			System.out.println("删除 Response: " + responseContent);
		} catch (IOException e) {
			e.printStackTrace();
			return "失败";
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
					return "失败";
				}
			}
		}
		return responseContent;
	}
	
	// AI解释文件
	// 从服务器拿到目标文本文档内容
	public String ai_files(String account, String password,String filesID) { 
		String url = "http://10.157.0.7:6767/manage/ai"; // 请求URL
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost build = new HttpPost(url);
		MultipartEntityBuilder builder = MultipartEntityBuilder.create();

		builder.addTextBody("account", account, ContentType.TEXT_PLAIN);
		builder.addTextBody("password", password, ContentType.TEXT_PLAIN);
		builder.addTextBody("filesID", filesID, ContentType.TEXT_PLAIN);

		HttpEntity multipart = builder.build();
		build.setEntity(multipart);

		CloseableHttpResponse response = null;
		String responseContent = null;
		try {
			response = httpClient.execute(build);
			HttpEntity responseEntity = response.getEntity();
			responseContent = EntityUtils.toString(responseEntity);
			System.out.println("POST Response is: " + responseContent);
			// 传入内容
			String AIContent=ai_files_to(responseContent);
			return AIContent;
		} catch (IOException e) {
			e.printStackTrace();
			return "失败";
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
					return "失败";
				}
			}
		}
	}

	// 拿到文本内容后调用服务器
	public String ai_files_to(String content) { 
		String decodedResult="";
		String url = "http://10.149.112.82:6767/manage/ai"; // 请求URL
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost build = new HttpPost(url);
		MultipartEntityBuilder builder = MultipartEntityBuilder.create();

		builder.addTextBody("token", "111111", ContentType.TEXT_PLAIN);
		builder.addTextBody("content", URLEncoder.encode(content), ContentType.TEXT_PLAIN);

		HttpEntity multipart = builder.build();
		build.setEntity(multipart);

		CloseableHttpResponse response = null;
		String responseContent = null;
		System.out.println("解释:"+content);
		//解析内容
	    try {
	        response = httpClient.execute(build);
	        HttpEntity responseEntity = response.getEntity();
	        responseContent = EntityUtils.toString(responseEntity);
	        System.out.println(responseContent);
	        JSONObject jsonObject = new JSONObject(responseContent);
	        String result = jsonObject.getString("result");
	        decodedResult = URLDecoder.decode(result, StandardCharsets.UTF_8.name());
	        return decodedResult;
	    } catch (IOException e) {
	        e.printStackTrace();
	        return "失败";
	    } finally {
	        if (response != null) {
	            try {
	                response.close();
	            } catch (IOException e) {
	                e.printStackTrace();
	                return "失败";
	            }
	        }
	    }
	}
	
	// 注销用户
	public String WriteOffUser(String account, String password) {
		String url = "http://10.157.0.7:6767/manage/delete/all"; // 请求URL
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost build = new HttpPost(url);
		MultipartEntityBuilder builder = MultipartEntityBuilder.create();

		builder.addTextBody("account", account, ContentType.TEXT_PLAIN);
		builder.addTextBody("password", password, ContentType.TEXT_PLAIN);
		HttpEntity multipart = builder.build();
		build.setEntity(multipart);

		CloseableHttpResponse response = null;
		String responseContent = null;
		try {
			response = httpClient.execute(build);
			HttpEntity responseEntity = response.getEntity();
			responseContent = EntityUtils.toString(responseEntity);
			System.out.println("注销 Response: " + responseContent);
		} catch (IOException e) {
			e.printStackTrace();
			return "失败";
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
					return "失败";
				}
			}
		}
		return responseContent;
	}

	// 重命名文件
	public String rename_file(String account, String password, String filePath, String new_name) {
		String url = "http://10.157.0.7:6767/manage/rename"; // 请求URL
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost build = new HttpPost(url);
		MultipartEntityBuilder builder = MultipartEntityBuilder.create();
		builder.addTextBody("account", account, ContentType.TEXT_PLAIN);
		builder.addTextBody("password", password, ContentType.TEXT_PLAIN);
		builder.addTextBody("file_path", URLEncoder.encode(filePath), ContentType.TEXT_PLAIN);
		builder.addTextBody("new_name", URLEncoder.encode(new_name), ContentType.TEXT_PLAIN);

		HttpEntity multipart = builder.build();
		build.setEntity(multipart);

		CloseableHttpResponse response = null;
		String responseContent = null;
		try {
			response = httpClient.execute(build);
			HttpEntity responseEntity = response.getEntity();
			responseContent = EntityUtils.toString(responseEntity);
			System.out.println("重命名 Response: " + responseContent);
		} catch (IOException e) {
			e.printStackTrace();
			return "失败";
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
					return "失败";
				}
			}
		}
		return responseContent;
	}

}
